<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body{
      margin: 0;
      padding: 0;
      background-color: rgba(0,0,0,0.05);
    }
    #canvas{
      position: fixed;
      z-index: -1;
    }
  </style>
  <script>
    var canvas, ctx
    var lineArr = []
    var inWidth = window.innerWidth,  inHeight = window.innerHeight
    var mousePos = {
      x: inWidth / 2,
      y: inHeight / 2
    }
    window.onmousemove = function(e) {
      mousePos.x = e.clientX
      mousePos.y = e.clientY
    }
    window.onresize = function () {
      resize()
    }
    // 初始化
    function init() {
      canvas = document.getElementById('canvas')
      ctx = canvas.getContext('2d')
      console.log(getRandomColor())
      for (var i=0; i<10; i++) {
        var line = new LineOb(inWidth / 2, inHeight / 2, 5, 'red', 2)
        lineArr.push(line)
      }
      ctx.lineWidth = 2
      ctx.globalAlpha = 0.5
      resize()
      anim()
    }

    // 绘制线条相关对象
    function LineOb(x, y, lineWidth, color, speed) {
      this.x = x
      this.y = y
      this.lineWidth = lineWidth // 线条宽度
      this.color = color // 颜色
      this.r = Math.random() * 150 // 半径
      this.speed = speed // 速率
      this.radian = Math.random() * Math.PI * 2 // 弧度
      this.draw = function() {
        var lastPos = {
          x: this.x,
          y: this.y
        }
        this.radian += speed
        this.x = mousePos.x + Math.cos(this.radian) * this.r
        this.y = mousePos.y + Math.sin(this.radian) * this.r
        ctx.beginPath()
        ctx.strokeStyle = this.color
        ctx.lineWidth = this.lineWidth
        ctx.moveTo(lastPos.x, lastPos.y)
        ctx.lineTo(this.x, this.y)
        ctx.stroke()
        ctx.closePath()
      }
    }

    // 获取随机颜色
    function getRandomColor() {
      var result = '#'
      var color = '0123456789ABCDF'
      for (var i=0; i<6; i++) {
        result += color[Math.ceil(Math.random() * 15)]
      }
      return result
    }

    // 监听窗口大小调整函数
    function resize() {
      inWidth = window.innerWidth
      inHeight = window.innerHeight
      canvas.width = inWidth
      canvas.height = inHeight
      for (var i=0; i<100; i++) {
        lineArr[i] = new LineOb(inWidth / 2,inHeight / 2,4,getRandomColor(),0.02);
      }
    }

    // 执行动画
    function anim() {
      window.requestAnimationFrame(anim)  
      // ctx.clearRect(0, 0, inWidth, inHeight)
      ctx.fillStyle = 'rgba(0,0,0,0.05)'
      ctx.fillRect(0, 0, inWidth, inHeight)
      for (var i=0; i<lineArr.length; i++) {
        lineArr[i].draw()
      }
    }
  </script>
</head>
<body onload="init()">
  <canvas id="canvas"></canvas>
</body>
</html>